package com.sky.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.sky.constant.MessageConstant;
import com.sky.exception.UploadPicFailedException;
import com.sky.properties.AliOssProperties;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

@Slf4j
@Component
public class AliOssUtil {

    @Autowired
    private AliOssProperties aliOssProperties;
    public  String uploadFile(String objectName, InputStream file){
        OSS ossClient = new OSSClientBuilder().build(
                aliOssProperties.getEndpoint(),
                aliOssProperties.getAccessKeyId(),
                aliOssProperties.getAccessKeySecret());
        try {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    aliOssProperties.getBucketName(),
                    objectName,
                    file);
            ossClient.putObject(putObjectRequest);
        }catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
        }catch (Exception e){
            throw new UploadPicFailedException(MessageConstant.UPLOAD_FAILED);
        }
        finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        String url="https://"+aliOssProperties.getBucketName()
                +"."+
                aliOssProperties.getEndpoint().substring(aliOssProperties.getEndpoint().lastIndexOf("/")+1)+"/"+objectName;
        log.info("上传了一个文件,路径{}",url);
        return url;
    }
}
